<template>
  <header>
    <div class="search-return" @click="goBack">
      <i class="iconfont icon-weibiaoti--"></i>
    </div>
    <div class="search-main">
      <i class="iconfont icon-fangdajing"></i>
      <form action="" onsubmit="return false" @keyup.enter="goSearchList">
        <input
          ref="searchGoods"
          type="search"
          placeholder="搜索您喜欢的产品..."
          v-model.trim="searchValue"
        />
      </form>
    </div>
    <div class="search-btn" @click="goSearchList">搜索</div>
  </header>
</template>

<script>
export default {
  name: "SearchHeader",
  data() {
    return {
      searchValue: this.$route.query.key || "",
      searchArr: [],
    };
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    goSearchList() {
      //空白不搜索
      if (!this.searchValue) return;
      //没有历史记录，创建一个本地存储
      if (!localStorage.getItem("searchList")) {
        localStorage.setItem("searchList", "[]");
      } else {
        this.searchArr = JSON.parse(localStorage.getItem("searchList"));
      }

      this.searchArr.unshift(this.searchValue);
      //es6去重
      let newArr = new Set(this.searchArr);
      //添加搜索历史记录
      localStorage.setItem("searchList", JSON.stringify(Array.from(newArr)));

      //重复搜索不跳转
      if (this.searchValue === this.$route.query.key) return;

      //跳转
      this.$router.push({
        name: "goods",
        query: {
          key: this.searchValue,
        },
      });
    },
  },

  mounted() {
    this.$nextTick(() => {
      this.$refs.searchGoods.focus(); //输入框默认获取焦点
    });
  },
};
</script>

<style scoped>
header {
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 100%;
  height: 1.173333rem;
  background-color: #b0252f;
  color: #fff;
}
.search-return,
.search-btn {
  padding: 0 0.266666rem;
}
.search-return i {
  height: 0.8rem;
  font-size: 0.7rem;
  line-height: 1.173333rem;
  text-align: center;
}

.search-main {
  display: flex;
  flex: 1;
  align-items: center;
  background-color: #fff;
  height: 0.8rem;
  border-radius: 12px;
  font-size: 0.426666rem;
}
.search-main i {
  color: #ccc;
  padding: 0 0.266666rem;
  font-size: 0.426666rem;
}

.search-main form {
  flex: 1;
}
.search-main input {
  width: 100%;
  font-size: 0.426666rem;
  color: #000;
}

.search-btn {
  font-size: 0.426666rem;
}
</style>